
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "IO.h"


//#define Test_mode 1
#define Scanning_accuracy 10 // us
#define Scanning_cycle 100 // ms
#define Number_of_trigger_pulses 10 // cnt
#define HL1_Relay_on_time		100 // ms
#define HL2_Relay_on_time		100 // ms


uint8_t pi1s;
uint16_t pi1pc = 0;
uint32_t hl1ontime = 0; 

uint8_t pi2s;
uint16_t pi2pc = 0;
uint32_t hl2ontime = 0; 


void test_mode(void)
{
	
		LED1_ON;
		LED2_ON;
		HL1_ON;
		HL2_ON;
		HL3_ON;
		HL4_ON;
		
		
		while(1)
		{
			
				//printf("%d	%d	\r\n",PWM_IN1,PWM_IN2);
				//delay_ms(500);
			
				if(PWM_IN1)
				{
						HL1_ON;
				}
				else
				{
						HL1_OFF;
				}
				
				if(PWM_IN2)
				{
						HL2_ON;
				}
				else
				{
						HL2_OFF;
				}
				
				if(PWM_IN3)
				{
						HL3_ON;
				}
				else
				{
						HL3_OFF;
				}
				
				if(PWM_IN4)
				{
						HL4_ON;
				}
				else
				{
					
						HL4_OFF;
				}
				
				
				
				
		}
		
}

uint32_t scanning_count = 0;
uint32_t work_led_count = 0;

 int main(void)
 { 
	IO_Init();
	delay_init();
	uart_init(115200);
	 
	 
	pi1s = PWM_IN1; 
	pi2s = PWM_IN2; 
	 
	#ifdef Test_mode
		
		test_mode();
	 
	#endif
	
	while(1)
	{
			if(pi1s != PWM_IN1)
			{
					pi1pc++;
			}
			pi1s = PWM_IN1;
			
			if(pi2s != PWM_IN2)
			{
					pi2pc++;
			}
			pi2s = PWM_IN2;
			
			if(pi1pc > Number_of_trigger_pulses)
			{
					HL1_ON;
					pi1pc = 0;
					hl1ontime = HL1_Relay_on_time * 100;
					
			}
			
			if(pi2pc > Number_of_trigger_pulses)
			{
					HL2_ON;
					pi2pc = 0;
					hl2ontime = HL2_Relay_on_time * 100;
					
			}
			
			if(hl1ontime > 0)
			{
					hl1ontime--;
			}
			else
			{
					HL1_OFF;
			}
			
			if(hl2ontime > 0)
			{
					hl2ontime--;
			}
			else
			{
					HL2_OFF;
			}
			
			delay_us(Scanning_accuracy);
			
			scanning_count++;
			
			if(scanning_count == Scanning_cycle * 1000)
			{
					pi1pc = 0;
					scanning_count = 0;
			}
			
			work_led_count++;
			if((work_led_count > 0)&&(work_led_count < 10000))
			{
					LED2_ON;
			}
			else
			{
					LED2_OFF;
			}
			if(work_led_count == 50000)
			{
					work_led_count = 0;
			}
			
			
	}
}
